package com.hongsen.cn.application;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ZysjSystemManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Environment;

import androidx.multidex.BuildConfig;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.alibaba.android.arouter.launcher.ARouter;
import com.facebook.cache.disk.DiskCacheConfig;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hongsen.cn.Utils.GsonUtils;
import com.hongsen.cn.Utils.LogUtil;
import com.hongsen.cn.Utils.SharedPreferencesUtil;
import com.hongsen.cn.Utils.Tools;
import com.hongsen.cn.Utils.Utils;
import com.hongsen.cn.Utils.Utils_CrashHandler;
import com.hongsen.cn.activity.MainActivity;
import com.hongsen.cn.bean.Config;
import com.hongsen.cn.bean.Constants;
import com.hongsen.cn.rest.HttpManager;
import com.hongsen.cn.service.InitService;
import com.tencent.bugly.crashreport.CrashReport;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Timer;
import java.util.TimerTask;

public class    DayAndMonthApplication extends MultiDexApplication {

    public boolean isShow = false;//日志开关

    public static int returnTime = 300;//循环更新时间（s)

    //log收集工具
    public static  Logger logger = LoggerFactory.getLogger(DayAndMonthApplication.class);

    public static DayAndMonthApplication intance;

    public static DayAndMonthApplication getInstance() {
        return intance;
    }

    /*本地配置文件*/
    public Config config = new Config();

    public Config getConfig() {
        return config;
    }

    public void setConfig(Config config) {
        this.config = config;
    }

    //倒计时锁定界面
    private boolean lockFlag = false;

    public boolean isLockFlag() {
        return lockFlag;
    }

    public void setLockFlag(boolean lockFlag) {
        this.lockFlag = lockFlag;
    }

    private int noOperationTimes = 0;

    public int getNoOperationTimes() {
        return noOperationTimes;
    }

    public void setNoOperationTimes(int noOperationTimes) {
        this.noOperationTimes = noOperationTimes;

    }

    //获取数据初始设置
    public SharedPreferences preferences;
    public SharedPreferences.Editor editor;

    private ZysjSystemManager mzysjSystemManager;

    public ZysjSystemManager getMzysjSystemManager() {
        return mzysjSystemManager;
    }


    public static Context mcontext;

    public static Context getContext() {
        return mcontext;
    }


    @SuppressLint("WrongConstant")
    @Override
    public void onCreate() {
        super.onCreate();
        this.intance = this;

        mcontext = getApplicationContext();

        //初始化日志工具类
        LogUtil.init(isShow);

        //初始化工具类
        Utils.init(this);

        //初始化bugly  a5ffc94c-b524-44ef-b458-a0789d80e0e7
        CrashReport.initCrashReport(getApplicationContext(), "ce39fae8c7", true);


        //Arouter
        if (BuildConfig.DEBUG) {
            ARouter.debuggable();
            ARouter.openLog();
        }
        ARouter.init(this);

        //图片缓存
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "frescocache");
        Fresco.initialize(this, ImagePipelineConfig.newBuilder(this).
                setMainDiskCacheConfig(
                        DiskCacheConfig.newBuilder(this)
                                .setBaseDirectoryPath(file)
                                .build()
                ).build());

        //读取本地文件
        loadConfig();

        //错误日志收集
        Utils_CrashHandler.getInstance().init(mcontext);

        //联网请求头配置
        if (StringUtils.isNotBlank(getCenterIp())) {
            HttpManager.getSingleton().initHttp(getCenterIp());
        } else {
            Tools.dispToast("服务器配置错误,请联系管理员");
        }

        //缓存相关
        SharedPreferencesUtil.init(this, "DayAndMonthObject");
        preferences = getSharedPreferences("preferences", MODE_PRIVATE);
        editor = preferences.edit();

        //隐藏任务栏
        mzysjSystemManager = (ZysjSystemManager) getSystemService("zysj");

        //
        Intent serviceIntent = new Intent(intance, InitService.class);
        startService(serviceIntent);

        //倒计时
        offScreenTimerOut();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();

    }

    /**
     * 无操作计时器
     */
    final Timer timer = new Timer();
    private void offScreenTimerOut() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (lockFlag) {
                    if (noOperationTimes == 90) {
                        setLockFlag(true);
                        Intent intent = new Intent(getBaseContext(), MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        getBaseContext().startActivity(intent);
                        noOperationTimes += 1;
                    } else {
                        noOperationTimes += 1;
                    }
                }
            }
        }, 0, 1000);
    }

    /**
     * 读取本地配置文件
     */
    private void loadConfig() {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            /*创建目录*/
            Tools.isFolderExists(Tools.getSDPath() + Constants.APP_ROOT_PATH);
            Tools.isFolderExists(Tools.getSDPath() + Constants.APP_CRASHLOG_PATH);
            Tools.isFolderExists(Tools.getSDPath() + Constants.APP_DOWNLOADS_PATH);
            Tools.isFolderExists(Tools.getSDPath() + Constants.APP_LOGS_PATH);
            Tools.isFolderExists(Tools.getSDPath() + Constants.APP_VIDEOS_PATH);
            Tools.isFolderExists(Tools.getSDPath() + Constants.APP_PICTURE_PATH);
            String path = Tools.getSDPath() + Constants.APP_ROOT_PATH;
            if (!Tools.fileIsExists(path + "/config.json")) {
                copyAssetsFile("config.json", path + "/config.json");
            }
            String configStr = getConfigJson(path + "/config.json");
            if (configStr != null) {
                config = objectMapper.readValue(configStr, Config.class);
                logger.debug(">>> ServerIp:" + config.getServerUrl());
            } else {
                logger.debug(">>> 配置文件不正确.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取本地文件中JSON字符串
     *
     * @param fileName 本地文件
     * @return JSON字符串
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private String getConfigJson(String fileName) {
        try {
            File file = new File(fileName);
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            return new String(buffer, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 拷贝配置assets
     *
     * @param from config.json;
     * @param to   /mnt/sdcard/outdor/config.json
     */
    public void copyAssetsFile(String from, String to) {
        try {
            if (!(new File(to)).exists()) {
                InputStream is = getResources().getAssets()
                        .open(from);
                FileOutputStream fos = new FileOutputStream(to);
                byte[] buffer = new byte[7168];
                int count;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getCenterIp() {
        if (StringUtils.isNotBlank(config.getServerUrl())) {
            return config.getServerUrl();
        }
        return "";
    }

}
